import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QMovie
from PyQt5.QtMultimedia import *
from PyQt5.uic import *
from PyQt5.QtWidgets import *

from DatabaseInteraction import DatabaseInteraction
from ui.fromfiledialog import Ui_FromFileDialog

class FromFileDialog(QDialog):
    def __init__(self):
        super(FromFileDialog, self).__init__()
        ui = Ui_FromFileDialog()
        self.ui = ui
        self.ui.setupUi(self)
        self.database_interaction = DatabaseInteraction()
        self.init_ui_set()
        self.init_ui_connect()
        self.player = None
        self.player_list = None
        self.media = None
        self.file_name = None

    def init_ui_set(self):
        self.init_class_box()
        self.init_annotation_label()

    def init_ui_connect(self):
        self.ui.pushButton.clicked.connect(self.click_select_address_button)
        self.ui.acceptButton.clicked.connect(self.accept)
        self.ui.rejectButton.clicked.connect(self.reject)

    #    理论上，init_ui_set和init_ui_connect两个方法，
    # 抽象层次上，是包括后续的方法的。更合理的设计方法，编者
    # 认为应该在上面的函数里嵌套函数。
    #
    #    但是由于笔者无法合理的在嵌套的函数中引用该类的参数，
    # 所以放弃了这个方法。望后来者改进。

    def init_class_box(self):
        for i in self.database_interaction.get_all_class():
            self.ui.classBox.addItem(i)

    def init_annotation_label(self):
        self.ui.IDLabel.setText(self.database_interaction.get_insert_id())

    def click_select_address_button(self):
        file = QFileDialog.getOpenFileNames(self, "打开文件", ".", "mp4 files(*.mp4)")
        if not file[0]:
            return
        self.file_name = file[0][0]
        self.ui.addressLabel.setText(f"你选择的地址为：\n{self.file_name}")
        self.ui.addressLabel.setScaledContents(True)

        # 设置放映影片
        self.player = QMediaPlayer()
        self.player_list = QMediaPlaylist()
        self.media = QMediaContent(QUrl.fromLocalFile(self.file_name))
        self.player.setPlaylist(self.player_list)
        self.player_list.addMedia(self.media)
        self.player.setVideoOutput(self.ui.videoWidget)
        self.player.setVolume(0)
        self.player.play()

    def accept_button(self):
        self.add()
        self.ui.close()

    def reject_button(self):
        self.ui.close()

    def add(self):
        pass

if __name__ == '__main__':
    app = QApplication(sys.argv)
    FromFileDialog = FromFileDialog()
    FromFileDialog.show()
    sys.exit(app.exec_())
